package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"
)

const (
	chromiumStatusURL = "http://chromium-status.appspot.com/allstatus?format=json"
	timeLayout        = "2006-01-02 15:04:05"
)

var (
	autoCloserRegexp = regexp.MustCompile(`Tree is closed \(Automatic: .* on .* from .*: (.*)\)`)
)

type RawAction struct {
	Username          string `json: "username"`
	Date              string `json: "date"`
	Message           string `json: "message"`
	Can_Commit_Freely bool   `json: "can_commit_freely"`
	General_State     string `json: "general_state"`
}

type Action struct {
	Username          string
	Date              string
	Time              time.Time
	Message           string
	Can_Commit_Freely bool
	General_State     string
	Recipients        []string
}

func (a Action) String() string {
	var s []string
	s = append(s, a.Date)
	s = append(s, fmt.Sprintf("username: %s", a.Username))
	s = append(s, fmt.Sprintf("time: %s", a.Time.Format(timeLayout)))
	s = append(s, fmt.Sprintf("message: %s", a.Message))
	if a.Can_Commit_Freely {
		s = append(s, "can_commit_freely")
	}
	s = append(s, fmt.Sprintf("general_state: %s", a.General_State))
	if len(a.Recipients) > 0 {
		s = append(s, fmt.Sprintf("recipients: %v", a.Recipients))
	}
	return strings.Join(s, "\n")
}

type ChromiumStatus struct {
	*url.URL
	Actions []Action
}

func (cstatus *ChromiumStatus) fetch(c *http.Client) (err error) {
	resp, err := c.Get(cstatus.URL.String())
	if err != nil {
		return err
	}
	d := json.NewDecoder(resp.Body)
	var actions []RawAction
	err = d.Decode(&actions)
	for _, action := range actions {
		var a Action
		a.Username = action.Username
		a.Date = action.Date
		a.Time, _ = time.Parse(timeLayout, action.Date[:len(timeLayout)])
		a.Message = action.Message
		a.Can_Commit_Freely = action.Can_Commit_Freely
		a.General_State = action.General_State
		a.Recipients = append(a.Recipients, a.Username)
		if m := autoCloserRegexp.FindStringSubmatch(a.Message); m != nil {
			a.Recipients = append(a.Recipients, strings.Split(m[1], ", ")...)
		}
		cstatus.Actions = append(cstatus.Actions, a)
	}
	return nil
}

func main() {
	surl, err := url.Parse(chromiumStatusURL)
	if err != nil {
		panic(err)
	}
	c := &ChromiumStatus{URL: surl}
	err = c.fetch(&http.Client{})
	for _, action := range c.Actions {
		fmt.Printf("%s\n\n", action)
	}
}
